<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 钉钉回调相关服务 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\service;


use app\core\model\Enterprise;
use app\core\model\SiteModule;
use common\Encryption;
use common\Random;
use common\XXTEAEncryption;
use ding\ApiHelper;
use ding\model\CallbackTagEnum;
use think\Env;

class CallbackService {

    /**
     * 更新回调接口
     *
     * @param $eid
     * @param $openBefore
     * @param $openNow
     * @param $tags
     * @return bool|string
     * @throws \think\exception\DbException
     */
    public static function update($eid, $openBefore, $openNow, $tags) {
        $enterprise = Enterprise::get($eid);
        $apiHelper = new ApiHelper($enterprise, null);

        $domain = request()->domain();
        $url = $domain . "/core/enterprise.callback/index?eid=" . $enterprise['id'];
        $callback = $enterprise['callback'];
        if (!$callback) {
            $callback = [];
        }
        if (is_string($callback)) {
            $callback = json_decode($callback, true);
        }
        $token = fetch($callback, "token");
        $aesKey = fetch($callback, "aesKey");
        if (!$aesKey || !$token) {
            return "未设置token或aesKey";
        }

        if (!$openBefore) {
            if (!$openNow) {
                // 之前没有开通回调，现在也不开通，则不做处理
                return true;
            } else {
                // 之前没开通回调，现在要开通
                $response = $apiHelper->callBackRegisterCallBack(
                    $tags, $token, $aesKey, $url
                );
                if ($apiHelper->isError($response)) {
                    return $apiHelper->getLastStatusMsg();
                }
                return true;
            }
        } else {
            if (!$openNow) {
                // 之前开通了回调，现在不开通了
                $response = $apiHelper->callBackDeleteCallBack();
                if ($apiHelper->isError($response)) {
                    return $apiHelper->getLastStatusMsg();
                }
                return true;
            } else {
                // 之前开通了回调，现在要继续开通，则更新tags
                $response = $apiHelper->callBackUpdateCallBack($tags, $token, $aesKey, $url);
                if ($apiHelper->isError($response)) {
                    return $apiHelper->getLastStatusMsg();
                }
                return true;
            }
        }
    }

}